package com.example.myapplication;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class MainActivity extends AppCompatActivity {
    private String host = "tcp://192.168.43.253:1883";
    private String userName = "android";
    private String passWord = "android";
    private String mqtt_id = "565402462";
    private String topic_temp = "temeperature";
    private String topic_humi = "humidity";
    private String mqtt_sub_topic = "565402462";
    private String mqtt_pub_topic = "565402462_ESP";
    private String mqtt_fan_topic = "fan_c";
    private String mqtt_window_topic = "window_c";
    private String mqtt_rain_topic = "rain";
    private int led_flag =0;
    private int fan_flag = 0;
    private int window_flag = 0;
    private ScheduledExecutorService scheduler;
    private ImageView image_light;
    private ImageView image_fan;
    private ImageView image_window;
    private TextView text_test;
    private TextView text_test2;
    private MqttClient client;
    private MqttConnectOptions options;
    private Handler handler;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ActionBar actionBar = getActionBar();
        if (actionBar != null) {
            actionBar.hide();
        }
        image_light =findViewById(R.id.image_1);
        image_fan = findViewById(R.id.fan);
        image_window = findViewById(R.id.image_window);
        //灯泡监听事件
        image_light.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) { ;
                if(led_flag == 0)
                {
                    publishmessageplus(mqtt_pub_topic,"ledOn");
                    Toast.makeText(MainActivity.this,"客厅灯打开" ,Toast.LENGTH_SHORT).show();
                    image_light.setImageResource(R.mipmap.light_on);
                    led_flag =1;
                }else{
                    publishmessageplus(mqtt_pub_topic,"ledOff");
                    Toast.makeText(MainActivity.this,"客厅灯关闭" ,Toast.LENGTH_SHORT).show();
                    image_light.setImageResource(R.mipmap.light);
                    led_flag =0;
                }
            }
        });
        //风扇监听事件
        image_fan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(fan_flag == 0)
                {
                    publishmessageplus(mqtt_fan_topic,"fanOn");
                    Toast.makeText(MainActivity.this,"风扇打开" ,Toast.LENGTH_SHORT).show();
                    image_fan.setImageResource(R.mipmap.fan);
                    fan_flag =1;
                }else{
                    publishmessageplus(mqtt_fan_topic,"fanOff");
                    Toast.makeText(MainActivity.this,"风扇关闭" ,Toast.LENGTH_SHORT).show();
                    image_fan.setImageResource(R.mipmap.fan_closed);
                    fan_flag =0;
                }
            }
        });
        //舵机监听事件
        image_window.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(window_flag == 0)
                {
                    publishmessageplus(mqtt_window_topic,"window_open");
                    Toast.makeText(MainActivity.this,"窗户打开" ,Toast.LENGTH_SHORT).show();
                    image_window.setImageResource(R.mipmap.window);
                    window_flag =1;
                }else{
                    publishmessageplus(mqtt_window_topic,"window_close");
                    Toast.makeText(MainActivity.this,"窗户关闭" ,Toast.LENGTH_SHORT).show();
                    image_window.setImageResource(R.mipmap.window_closed);
                    window_flag =0;
                }
            }
        });
        text_test =findViewById(R.id.text_test);
        text_test2 =findViewById(R.id.text_test2);

        Mqtt_init();
        startReconnect();
        handler = new Handler(Looper.myLooper()) {
            @SuppressLint("SetTextI18n")
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what){
                    case 1:
                        image_window.setImageResource(R.mipmap.window_closed);
                        break;
                    case 2:
                        String Hval = msg.obj.toString()+"℃";
                        text_test2.setText(Hval);
                        break;
                    case 3:
                        String T_val = msg.obj.toString();
                        String text_val = T_val+" %";
                        text_test.setText(text_val);
                        break;
                    case 30:
                        Toast.makeText(MainActivity.this,"连接失败" ,Toast.LENGTH_SHORT).show();
                        break;
                    case 31:   //连接成功
                        Toast.makeText(MainActivity.this,"连接成功" ,Toast.LENGTH_SHORT).show();
                        try {
                            client.subscribe(mqtt_sub_topic,1);
                            client.subscribe(topic_temp);
                            client.subscribe(topic_humi);
                            client.subscribe(mqtt_rain_topic);
                        } catch (MqttException e) {
                            e.printStackTrace();
                        }
                        break;
                    default:
                        break;
                }
            }
        };

    }
    private void Mqtt_init() {
        try {
            client = new MqttClient(host, mqtt_id, new MemoryPersistence());
            options = new MqttConnectOptions();
            options.setCleanSession(false);
            options.setUserName(userName);
            options.setPassword(passWord.toCharArray());
            options.setConnectionTimeout(10);
            options.setKeepAliveInterval(20);
            client.setCallback(new MqttCallback() {
                @Override
                public void connectionLost(Throwable cause) {
                    System.out.println("connectionLost----------");
                }
                @Override
                public void deliveryComplete(IMqttDeliveryToken token) {
                    System.out.println("deliveryComplete---------" + token.isComplete());
                }
                @Override
                public void messageArrived(String topicName, MqttMessage message) throws Exception {
                    System.out.println("messageArrived----------");
                    Message msg = new Message();
                    if(topicName.equals("humidity")){
                        msg.what = 3;
                    }else if(topicName.equals("temeperature")){
                        msg.what = 2;
                    }else if (topicName.equals("rain")){
                        msg.what = 1;
                    }
                    msg.obj = message.toString();
                    handler.sendMessage(msg);
                    System.out.println("handler传递了"+msg.toString());
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    private void Mqtt_connect() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    if(!(client.isConnected()) )
                    {
                        client.connect(options);
                        Message msg = new Message();
                        msg.what = 31;
                        handler.sendMessage(msg);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    Message msg = new Message();
                    msg.what = 30;
                    handler.sendMessage(msg);
                }
            }
        }).start();
    }
    private void startReconnect() {
        scheduler = Executors.newSingleThreadScheduledExecutor();
        scheduler.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                if (!client.isConnected()) {
                    Mqtt_connect();
                }
            }
        }, 0 * 1000, 10 * 1000, TimeUnit.MILLISECONDS);
    }
    private void publishmessageplus(String topic,String message2)
    {
        if (client == null || !client.isConnected()) {
            return;
        }
        MqttMessage message = new MqttMessage();
        message.setPayload(message2.getBytes());
        try {
            client.publish(topic,message);
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }
}